package com.lt.demo.controller;

import com.lt.demo.domain.User;
import com.lt.demo.service.UserService;
import com.lt.demo.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "根据用户账户和密码进行注册")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "成功注册")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "100", description = "已经被注册")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "300", description = "内部异常")
    public ApiResponse<String> register(@RequestBody @Parameter User user) {
        User user1 = userService.findByUsername(user.getUsername());
        if (user1 != null) {
            return new ApiResponse<>(100, "Username has registered !", null);
        }
        userService.register(user);
        return new ApiResponse<>(200, "User registered successfully", null);
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "根据用户账户和密码进行登录，返回token")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "成功登录")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "300", description = "内部异常")
    public ApiResponse<String> login(@RequestBody @Parameter  User user) {
        try {
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
        } catch (Exception e) {
            throw new UsernameNotFoundException("Invalid username or password");
        }
        UserDetails userDetails = userService.loadUserByUsername(user.getUsername());
        String token = jwtUtil.generateToken(userDetails.getUsername());
        return new ApiResponse<>(200, "Login successful", token);
    }
}